package com.czg.jsonschema2lombokpojo;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import com.sun.codemodel.JPackage;
import com.sun.codemodel.util.UnicodeEscapeWriter;

/**
 * 尊重给定字符编码的编写器（解决{@link com.sun.codemodel.util.EncoderFactory#createEncoder(String)}导致给定编码被忽略的问题）。
 */
public class FileCodeWriterWithEncoding extends com.sun.codemodel.writer.FileCodeWriter {

    public FileCodeWriterWithEncoding(File target, String encoding) throws IOException {
        super(target, encoding);
    }

    @Override
    public Writer openSource(JPackage pkg, String fileName) throws IOException {
        final Writer bw = new OutputStreamWriter(openBinary(pkg, fileName), encoding);

        return new UnicodeEscapeWriter(bw) {
            private final CharsetEncoder encoder = Charset.forName(encoding).newEncoder();

            @Override
            protected boolean requireEscaping(int ch) {
                // control characters
                if (ch < 0x20 && " \t\r\n".indexOf(ch) == -1) {
                    return true;
                }
                // ASCII chars
                if (ch < 0x80) {
                    return false;
                }
                return !encoder.canEncode((char) ch);
            }
        };
    }

}
